package io.mqtt.test;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author tianzhenjiu
 * @date 2020/9/17 14:45
 */
public class HttpCallbackHandle extends ChannelInboundHandlerAdapter {

    Logger logger = LoggerFactory.getLogger(HttpCallbackHandle.class);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(!(msg instanceof FullHttpResponse)){
            logger.info("收到非HTTPresponse报文");
            return;
        }


        FullHttpResponse fullHttpResponse=(FullHttpResponse) msg;
        logger.info("status{}",fullHttpResponse.status());
        HttpHeaders httpHeaders=fullHttpResponse.headers();
        httpHeaders.forEach((h)->{
            logger.info(h.getKey()+"=>"+h.getValue());
        });

        ByteBuf httpContent=fullHttpResponse.content();
        byte [] bytes = new byte [httpContent.readableBytes()];
        httpContent.readBytes(bytes);
        logger.info("=>"+new String(bytes));

        ctx.close();

    }


}
